package softwaredepartment.zxit.com.pt_3280cinandroid;

import android.content.ContentResolver;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.kyleduo.switchbutton.SwitchButton;
import com.socks.library.KLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.LinkedList;

public class BroadcastTalkingActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout volumeState;
    private Button bt_back, bt_into_tutorial, bt_switch_mode;
    private TextView tv_font_startTalk, tv_fontSize_small, tv_fontSize_large, tv_fontSize_middle, tv_all_screen, tv_get_fileList, tv_speech;
    private LinearLayout ll_switch_broadcast;
    private ImageView ic_volume_state;
    private SeekBar sb_adjust_volume;
    private ScrollView sv_speech;
    private Chronometer chronometer_timer;
    private Boolean i$Talk = false;
    private Boolean i$Switch = false;
    private SwitchButton OpenProtocol;
    private FileOutputStream fileOutputStream;

    private float mVolume = (float) 0.2;
    /**
     *
     */
    public Boolean flag = true;

    /**
     * AudioRecord 写入缓冲区大小
     */
    protected int m_in_buf_size;
    /**
     * 录制音频对象
     */
    private AudioRecord m_in_rec;
    /**
     * 录入的字节数组
     */
    private byte[] m_in_bytes;
    /**
     * 存放的大小
     */
    private LinkedList<byte[]> m_in_q;


    /**
     * 控制音响开基础格式 INT
     */
    public int[] ControllerHeader = {
            0x29, 0x01, 0x00, 0xf4, 0x00, 0x01, 0x1b, 0x58, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
    /**
     * 控制文音响关基础格式 INT
     */
    public int[] ControllerHeaderClose = {
            0x29, 0x00, 0x00, 0xf4, 0x00, 0x01, 0x1b, 0x58, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
            0x01, 0x01, 0x01, 0x01, 0x01, 0x01};
    /**
     * 控制文件开基础格式 BYTE
     */
    public byte[] Controller_byte = new byte[248];
    /**
     * 控制文音响关基础格式 BYTE
     */
    public byte[] Controller_byte_close = new byte[248];
    /**
     * 广播地址
     */
    public InetAddress serverAddress;
    /**
     * 控制协议UDP对象
     */
    public DatagramSocket socketController;
    /**
     * 发送音频UDP对象
     */
    public DatagramSocket socketAudio;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        setContentView(R.layout.activity_broadcast_talking);
        initView();
        initParams();

        OpenProtocol.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                try {
                    if (isChecked) {
                        //开启
                        Thread controllerOpenThread = new Thread(new BroadcastTalkingActivity.controllerOpen());
                        controllerOpenThread.start();
                        i$Switch = true;
                    } else {
                        //关闭
                        Thread controllerCloseThread = new Thread(new BroadcastTalkingActivity.controllerClose());
                        controllerCloseThread.start();
                        i$Switch = false;
                    }
                } catch (Exception e) {
                    OpenProtocol.setVisibility(isChecked ? View.VISIBLE : View.INVISIBLE);
                    Toast.makeText(getApplication(), "控制协议发送失败！建议重新启动APP或者联系管理员。", Toast.LENGTH_SHORT).show();
                }
            }
        });

        sb_adjust_volume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mVolume = (float) (progress / 80.00 * 0.2);
                if (0 < progress && progress <= 25) {
                    ic_volume_state.setImageDrawable(getResources().getDrawable(R.mipmap.ic_volume_1));
                }if(25 < progress && progress <= 50){
                    ic_volume_state.setImageDrawable(getResources().getDrawable(R.mipmap.ic_volume_2));
                }if(50 < progress && progress <= 75){
                    ic_volume_state.setImageDrawable(getResources().getDrawable(R.mipmap.ic_volume_3));
                }if(75 < progress && progress < 100){
                    ic_volume_state.setImageDrawable(getResources().getDrawable(R.mipmap.ic_volume_4));
                }if(progress ==0){
                    ic_volume_state.setImageDrawable(getResources().getDrawable(R.mipmap.ic_volume));
                }if(progress ==100){
                    ic_volume_state.setImageDrawable(getResources().getDrawable(R.mipmap.ic_volume_89));
                }



            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    private void initParams() {
        // AudioRecord 得到录制最小缓冲区的大小
        m_in_buf_size = AudioRecord.getMinBufferSize(8000,
                AudioFormat.CHANNEL_CONFIGURATION_STEREO ,
                AudioFormat.ENCODING_PCM_16BIT);
        // 实例化播放音频对象
        m_in_rec = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000,
                AudioFormat.CHANNEL_CONFIGURATION_STEREO ,
                AudioFormat.ENCODING_PCM_16BIT, m_in_buf_size);
        // 实例化一个字节数组，长度为最小缓冲区的长度
        m_in_bytes = new byte[m_in_buf_size];
        // 实例化一个链表，用来存放字节组数
        m_in_q = new LinkedList<>();//byte[]

        for (int i = 0; i < ControllerHeader.length; i++) {
            Controller_byte[i] = (byte) ControllerHeader[i];
        }
        for (int i = 0; i < ControllerHeaderClose.length; i++) {
            Controller_byte_close[i] = (byte) ControllerHeaderClose[i];
        }


        //初始化UDP的相应参数
        try {
            serverAddress = InetAddress.getByName("255.255.255.255");
            socketController = new DatagramSocket(6003);
            socketAudio = new DatagramSocket(7001);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        int mic_bg_width = (int) ((double) (volumeState.getHeight()) * 64.00 / 156.00);
        int mic_bg_height = volumeState.getHeight();
        LinearLayout.LayoutParams volumeState_prams = new LinearLayout.LayoutParams(mic_bg_width, mic_bg_height);
        volumeState.setLayoutParams(volumeState_prams);
    }

    private void initView() {
        volumeState = (LinearLayout) findViewById(R.id.volumeState);
        bt_back = (Button) findViewById(R.id.bt_back);
        bt_into_tutorial = (Button) findViewById(R.id.bt_into_tutorial);
        bt_switch_mode = (Button) findViewById(R.id.bt_switch_mode);
        tv_font_startTalk = (TextView) findViewById(R.id.tv_font_startTalk);
        chronometer_timer = (Chronometer) findViewById(R.id.chronometer_timer);
        tv_fontSize_small = (TextView) findViewById(R.id.tv_fontSize_small);
        tv_fontSize_large = (TextView) findViewById(R.id.tv_fontSize_large);
        tv_fontSize_middle = (TextView) findViewById(R.id.tv_fontSize_middle);
        tv_all_screen = (TextView) findViewById(R.id.tv_all_screen);
        tv_get_fileList = (TextView) findViewById(R.id.tv_get_fileList);
        tv_speech = (TextView) findViewById(R.id.tv_speech);
        ll_switch_broadcast = (LinearLayout) findViewById(R.id.ll_switch_broadcast);
        ic_volume_state = (ImageView) findViewById(R.id.ic_volume_state);
        sb_adjust_volume = (SeekBar) findViewById(R.id.sb_adjust_volume);
        sv_speech = (ScrollView) findViewById(R.id.sv_speech);
        OpenProtocol = (SwitchButton) this.findViewById(R.id.isOpenProtocol);

        ll_switch_broadcast.setOnClickListener(this);
        bt_into_tutorial.setOnClickListener(this);
        bt_back.setOnClickListener(this);
        bt_switch_mode.setOnClickListener(this);
    }


    private byte[] WriteWaveFileHeader(long totalAudioLen,long totalDataLen, long longSampleRate, int channels, long byteRate)
            throws IOException {
        byte[] header = new byte[44];
        header[0] = 'R'; // RIFF/WAVE header
        header[1] = 'I';
        header[2] = 'F';
        header[3] = 'F';
//        header[4] = (byte) (totalDataLen & 0xff);
//        header[5] = (byte) ((totalDataLen >> 8) & 0xff);
//        header[6] = (byte) ((totalDataLen >> 16) & 0xff);
//        header[7] = (byte) ((totalDataLen >> 24) & 0xff);
        header[4] = 0;
        header[5] = (byte) (0x01);
        header[6] = 0;
        header[7] = 0;
        header[8] = 'W';
        header[9] = 'A';
        header[10] = 'V';
        header[11] = 'E';
        header[12] = 'f'; // 'fmt ' chunk
        header[13] = 'm';
        header[14] = 't';
        header[15] = ' ';
        header[16] = 16; // 4 bytes: size of 'fmt ' chunk
        header[17] = 0;
        header[18] = 0;
        header[19] = 0;
        header[20] = 1; // format = 1
        header[21] = 0;
        header[22] = (byte) channels;
        header[23] = 0;
        header[24] = (byte) (longSampleRate & 0xff);
        header[25] = (byte) ((longSampleRate >> 8) & 0xff);
        header[26] = (byte) ((longSampleRate >> 16) & 0xff);
        header[27] = (byte) ((longSampleRate >> 24) & 0xff);
        header[28] = (byte) (byteRate & 0xff);
        header[29] = (byte) ((byteRate >> 8) & 0xff);
        header[30] = (byte) ((byteRate >> 16) & 0xff);
        header[31] = (byte) ((byteRate >> 24) & 0xff);
        header[32] = (byte) (2 * 16 / 8); // block align
        header[33] = 0;
        header[34] = 16; // bits per sample
        header[35] = 0;
        header[36] = 'd';
        header[37] = 'a';
        header[38] = 't';
        header[39] = 'a';
//        header[40] = (byte) (totalAudioLen & 0xff);
//        header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
//        header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
//        header[43] = (byte) ((totalAudioLen >> 24) & 0xff);
        header[40] = (byte) (0xcc);
        header[41] = (byte) (0xcc);
        header[42] = (byte) (0x4c);
        header[43] = (byte) (0x19);
        return header;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_into_tutorial:
                Toast.makeText(this, "此功能暂未开放！", Toast.LENGTH_SHORT).show();
                break;
            case R.id.bt_switch_mode:
                break;
            case R.id.ll_switch_broadcast:
                if (i$Talk) {
                    if (i$Switch) {
                        Toast.makeText(this, "请先取消控制协议！", Toast.LENGTH_SHORT).show();
                    } else {
                        flag =false;
                        tv_font_startTalk.setText("开始广播");
                        i$Talk = false;
                        chronometer_timer.stop();
                    }
                } else {
                    if (!i$Switch) {
                        Toast.makeText(this, "请先发送控制协议！", Toast.LENGTH_SHORT).show();
                    } else {
                        Thread recordSoundThread = new Thread(new BroadcastTalkingActivity.recordSound());
                        recordSoundThread.start();
                        chronometer_timer.setBase(SystemClock.elapsedRealtime());
                        chronometer_timer.start();
                        tv_font_startTalk.setText("关闭广播");
                        i$Talk = true;
                    }
                }
                break;
            default:
                break;


        }
    }

    /**
     * 录音线程（其中在录音的过程中已经将录音的Buffer传给音响的相应端口）
     */
    class recordSound implements Runnable {
        @Override
        public void run() {
            Log.i("Re0", "........麦克风开启了 下面开始录制您说话的声音......");
            byte[] bytes_pkg;
            // 开始录音
            m_in_rec.startRecording();
            try {
                fileOutputStream =new FileOutputStream("/data/data/softwaredepartment.zxit.com.pt_3280cinandroid/files/" +"test.txt",true);
                byte[] WAVHeader_byte = new byte[44];
                int[] WAVHeader = {
                        //52    49    46    46    00    01    00    00    57    41    56    45    66    6d    74    20
                        //10    00    00    00    01    00    02    00    40    1f    00    00    00    7d    00    00
                        //04    00    10    00    64    61    74    61    cc    cc    4c    19
                        0x52, 0x49, 0x46, 0x46, 0x00, 0x01, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20,
                        0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00,
                        0x04, 0x00, 0x10, 0x00, 0x64, 0x61, 0x74, 0x61, 0xcc, 0xcc, 0x4c, 0x19};



                for (int i = 0; i < WAVHeader.length; i++) {
                    WAVHeader_byte[i] = (byte) WAVHeader[i];
                }

                if (socketAudio == null) {
                    socketAudio = new DatagramSocket(null);
                    socketAudio.setReuseAddress(true);
                    socketAudio.bind(new InetSocketAddress(7001));
                }
                DatagramPacket sendPacket = new DatagramPacket(WriteWaveFileHeader(1,1,8000,2,16), WriteWaveFileHeader(2,2,8000,2,16).length, serverAddress, 7001);
                socketAudio.send(sendPacket);
                fileOutputStream.write(WriteWaveFileHeader(1,1,8000,2,16));

                while (flag) {
                    int r = m_in_rec.read(m_in_bytes, 0, m_in_buf_size);
                    long v = 0;
                    for (int i = 0; i < m_in_bytes.length; i++) {
                        v += m_in_bytes[i] * m_in_bytes[i];
                    }
                    double mean = v / (double) r;
                    double volume = 10 * Math.log10(mean);
                    Log.i("", volume + "");
                    /*
                    //r是实际读取的数据长度，一般而言r会小于buffersize
                    int r = audioRecord.read(b, 0, b.length);
                    long v = 0;
                    // 将 buffer 内容取出，进行平方和运算
                    for (int i = 0; i < b.length; i++) {
                         v += b[i] * b[i];
                    }
                    // 平方和除以数据总长度，得到音量大小。
                    double mean = v / (double) r;
                    double volume = 10 * Math.log10(mean);

                    wait++;
                    if(wait > maxWait){
                        wait = 0;
                        Log.d(this.getClass().getName(), "分贝值:" + volume + " " + (volume > 0));
                        if(volume > 0){
                            recordEnable = true;
                        }
                     */
                    for (int i = 0; i < m_in_bytes.length; i++) {
                        m_in_bytes[i] = (byte) (m_in_bytes[i] * mVolume);
                    }
                    bytes_pkg = m_in_bytes.clone();
                    int j = (bytes_pkg.length) / 256;
                    int k = 0;
                    for (int i = 1; i < (bytes_pkg.length) + 1; i++) {
                        if (i % 256 == 0 && i != 0) {
                            byte[] newData = Arrays.copyOfRange(bytes_pkg, k * 256, i);

                            sendPacket = new DatagramPacket(newData, newData.length, serverAddress, 7001);

                            socketAudio.send(sendPacket);
                            fileOutputStream.write(newData);
                            KLog.i("==测试底噪==");
                            k++;
                        }
                        if (i == bytes_pkg.length) {
                            byte[] newData;
                            newData = Arrays.copyOfRange(bytes_pkg, j * 256, i);
                            sendPacket = new DatagramPacket(newData, newData.length, serverAddress, 7001);

                            socketAudio.send(sendPacket);
                            fileOutputStream.write(newData);
                        }
                    }

                    //为什么不把直接的byte_pkg 直接传过去? 答 : 保证拿到的声音不会丢失
                    if (m_in_q.size() >= 2) {
                        m_in_q.removeFirst();
                    }
                    m_in_q.add(bytes_pkg);
                }
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 通过UDP 6003端口发送开启喇叭的控制协议
     */
    class controllerOpen implements Runnable {
        @Override
        public void run() {

            try {

                byte[] bytesToSend = Controller_byte;
                socketController.setSoTimeout(3000);
                DatagramPacket sendPacket = new DatagramPacket(bytesToSend, bytesToSend.length, serverAddress, 6003);
                socketController.send(sendPacket);

            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过UDP 6003端口发送关闭喇叭的控制协议
     */

    class controllerClose implements Runnable {
        @Override
        public void run() {

            try {

                byte[] bytesToSend = Controller_byte_close;
                socketController.setSoTimeout(3000);
                DatagramPacket sendPacket = new DatagramPacket(bytesToSend, bytesToSend.length, serverAddress, 6003);
                socketController.send(sendPacket);

            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void method3(String fileName, String content) {
        try {
            // 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
